/**
 * 
 */
package com.project.tructc.MBean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.RandomStringUtils;
import org.primefaces.event.FileUploadEvent;

import com.project.entity.Account;
import com.project.entity.Staff;
import com.project.nhantvt.SessionBean.EmployeeBeanRemote;
import com.project.ryudo.SessionBean.AccountBeanRemote;
import com.project.ryudo.SessionBean.StaffBeanRemote;
import com.project.util.MessageCall;

/**
 * @author RYUDO
 *
 */
@ManagedBean(name="mAccount")
@SessionScoped
public class MAccount {
	private Account acc;
	private Staff stf;
	private Account requestAccount;
	
	private String new_password;
	private String confirm_password;
	private String VerifiedString;
	private String GeneratedPassword;
	private String StaffAccType;
	private String RequestAccountVerifiedStatus;
	
	//Flag Variables
	boolean isLoggedIn;
	boolean ResetPassword;
	private boolean imageUploaded;
	private boolean isStaff;
	private boolean isAdmin;
	
	public MAccount() {
		acc = new Account();
		stf = new Staff();
	}

	public void setRequestAccountVerifiedStatus(
			String requestAccountVerifiedStatus) {
		RequestAccountVerifiedStatus = requestAccountVerifiedStatus;
	}

	public String getRequestAccountVerifiedStatus() {
		if(this.requestAccount.getIsVerified())
		{
			this.RequestAccountVerifiedStatus = "Verified";
		}
		else
		{
			this.RequestAccountVerifiedStatus = "Not Verified";
		}
		return this.RequestAccountVerifiedStatus;
	}

	public void setRequestAccount(Account requestAccount) {
		this.requestAccount = requestAccount;
	}

	public Account getRequestAccount() {
		return requestAccount;
	}

	public void setStaffAccType(String staffAccType) {
		StaffAccType = staffAccType;
	}

	public String getStaffAccType() {
		return StaffAccType;
	}

	public void setStf(Staff stf) {
		this.stf = stf;
	}

	public Staff getStf() {
		return stf;
	}

	public void setAdmin(boolean isAdmin) {
		this.isAdmin = isAdmin;
	}

	public boolean isAdmin() {
		return isAdmin;
	}

	public void setStaff(boolean isStaff) {
		this.isStaff = isStaff;
	}

	public boolean isStaff() {
		return isStaff;
	}

	public void setVerifiedString(String verifiedString) {
		VerifiedString = verifiedString;
	}

	public String getVerifiedString() {
		return VerifiedString;
	}

	/**
	 * @param imageUploaded the imageUploaded to set
	 */
	public void setImageUploaded(boolean imageUploaded) {
		this.imageUploaded = imageUploaded;
	}

	/**
	 * @return the imageUploaded
	 */
	public boolean isImageUploaded() {
		return imageUploaded;
	}

	public boolean isResetPassword() {
		return ResetPassword;
	}

	public void setResetPassword(boolean resetPassword) {
		ResetPassword = resetPassword;
	}

	public boolean isLoggedIn() {
		return isLoggedIn;
	}

	public void setLoggedIn(boolean isLoggedIn) {
		this.isLoggedIn = isLoggedIn;
	}

	public Account getAcc() {
		return acc;
	}

	public void setAcc(Account acc) {
		this.acc = acc;
	}
	
	public String getNew_password() {
		return new_password;
	}

	public void setNew_password(String new_password) {
		this.new_password = new_password;
	}

	public String getConfirm_password() {
		return confirm_password;
	}

	public void setConfirm_password(String confirm_password) {
		this.confirm_password = confirm_password;
	}

	public String getGeneratedPassword() {
		return GeneratedPassword;
	}

	public void setGeneratedPassword(String generatedPassword) {
		GeneratedPassword = generatedPassword;
	}

	public String Login() throws NamingException
	{
			Context ctx = new InitialContext();
			AccountBeanRemote accRe = (AccountBeanRemote) ctx
					.lookup("MySweetHome/AccountBean/remote");
			
			List result = accRe.LoginUserIn(acc.getEmail(), acc.getPassword());
			if (result.size() == 0) {
				this.acc = new Account();
				this.isLoggedIn = false;
				MessageCall.errorMessage("Username or Password incorrect !", "fm_login:acc_email");
				MessageCall.errorMessage("Username or Password incorrect !", "common-form:acc_email");
				return "Failed";
			}
			else {
				this.acc = (Account) result.get(0);
				this.GetStatusVerified();
				this.isLoggedIn = true;
				return "Logged";
			}
	}
	public String LoginStaff() throws NamingException
	{
			Context ctx = new InitialContext();
			StaffBeanRemote accRe = (StaffBeanRemote) ctx
					.lookup("MySweetHome/StaffBean/remote");
			
			List result = accRe.LoginStaffIn(stf.getEmail(), stf.getPassword());
			if (result.size() == 0) {
				this.stf = new Staff();
				this.isAdmin = false;
				this.isStaff = false;
				MessageCall.errorMessage("Username or Password incorrect !", "fm_login:acc_email");
				MessageCall.errorMessage("Username or Password incorrect !", "common-form:acc_email");
				return "StaffLoginFailed";
			}
			
			else {
				this.isStaff = true;
				if(this.stf.isAdmin())
				{
					this.isAdmin = true;
				} 
				else
				{
					this.isAdmin = false;
				}
				this.stf = (Staff) result.get(0);
		
				return "StaffLogged";
			}
	}
	
	public String Logout() {
		this.acc = new Account();
		
		this.isLoggedIn = false;
		this.imageUploaded = false;
		return "LoggedOut";
	}
	
	public String LogoutStaff()
	{
		this.stf = new Staff();
		this.isAdmin = false;
		this.isStaff = false;
		return "LoggedOutStaff";
	}
	
	public String generate_password() {
		this.GeneratedPassword = RandomStringUtils.randomAlphabetic(12);
		return this.GeneratedPassword;
	}
	
	public String forgot_password() throws NamingException {
		Context ctx = new InitialContext();
		AccountBeanRemote accRe = (AccountBeanRemote) ctx
				.lookup("MySweetHome/AccountBean/remote");
		List result = accRe.CheckEmail(acc.getEmail());
		if (result.size() != 0) {
			Account temp = (Account) result.get(0);
			
			if (temp.getQuestion().equals(acc.getQuestion())
					&& temp.getAnswer().equals(acc.getAnswer())) {
				this.acc = temp;
				this.acc.setPassword(this.generate_password());
				accRe.updateBasicInfo(acc);
				this.ResetPassword = true;
				this.acc = new Account();
				return "ok";
			} else {
				FacesMessage message = new FacesMessage(
						FacesMessage.SEVERITY_ERROR,
						"Security Question and Answer not match !",
						"Security Question and Answer not match !");
				FacesContext.getCurrentInstance().addMessage("forgot-password-form:forgot_email", message);
				return "";

			}
		} else {
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Account Not Found !",
					"Account Not Found !");
			FacesContext.getCurrentInstance().addMessage("", message);
			return "";
		}

	}
	
	public String updateNewPassword() throws NamingException {
		Context ctx = new InitialContext();
		AccountBeanRemote accRe = (AccountBeanRemote) ctx
				.lookup("MySweetHome/AccountBean/remote");
		if (this.new_password.equals(this.confirm_password)) {
			acc.setPassword(new_password);
			accRe.updateBasicInfo(acc);
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
					"Password update successfully !",
					"Password update successfully !");
			FacesContext.getCurrentInstance().addMessage(
					"change-password-form:check_password", message);
		} else {
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Password don't match !",
					"Password don't match !");
			FacesContext.getCurrentInstance().addMessage(
					"change-password-form:check_password", message);
		}
		return "";

	}
	
//******************* NHANTVT CODE *****************************************//
	
	public String updateStaffPassword() throws NamingException {
		Context ctx = new InitialContext();
		EmployeeBeanRemote accRe = (EmployeeBeanRemote) ctx
				.lookup("MySweetHome/EmployeeBean/remote");
		
		if (this.new_password.equals(this.confirm_password)) {
			stf.setPassword(new_password);
			accRe.UpdateStaff(stf);
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
					"Password update successfully !",
					"Password update successfully !");
			FacesContext.getCurrentInstance().addMessage(
					"change-password-form:check_password", message);
		
		} else {
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Password don't match !",
					"Password don't match !");
			FacesContext.getCurrentInstance().addMessage(
					"change-password-form:check_password", message);
		}
		
		return "";
	}
	
	public String updateStaffInfo() throws NamingException {
		Context ctx = new InitialContext();
		EmployeeBeanRemote accRe = (EmployeeBeanRemote) ctx
				.lookup("MySweetHome/EmployeeBean/remote");
		
		accRe.UpdateStaff(stf);
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Your information has updated successfully",
				"Your information has updated successfully");
		FacesContext.getCurrentInstance().addMessage("change-info-form:uinfo",
				message);
		return "";
	}

//******************* NHANTVT CODE *****************************************//
	
	public String updateBasicInfo() throws NamingException {
		Context ctx = new InitialContext();
		AccountBeanRemote accRe = (AccountBeanRemote) ctx
				.lookup("MySweetHome/AccountBean/remote");
		accRe.updateBasicInfo(acc);
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Your information has updated successfully",
				"Your information has updated successfully");
		FacesContext.getCurrentInstance().addMessage("change-info-form:uinfo",
				message);
		return "";
	}

	public String updateAccountInfo() throws NamingException {
		Context ctx = new InitialContext();
		AccountBeanRemote accRe = (AccountBeanRemote) ctx
				.lookup("MySweetHome/AccountBean/remote");
		accRe.updateBasicInfo(acc);
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
					"Your account information has updated successfully",
					"Your account information has updated successfully");
			FacesContext.getCurrentInstance().addMessage(
					"account-info-form:ainfo", message);
		
		return "";

	}
	
	public String view_user_profile(String id) throws NamingException
	{
		HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
		if(request.getParameter("uid") == null)
		{
			MessageCall.errorMessage("User not found !", "");
			return "NotFound";
		}
		else
		{
			Context ctx = new InitialContext();
			AccountBeanRemote accRe = (AccountBeanRemote) ctx
					.lookup("MySweetHome/AccountBean/remote");
			List result = accRe.loadRequestedUser(request.getParameter("uid"));
			if(result.size() != 0)
			{
				this.requestAccount = (Account)result.get(0);
				return "Found";
			}
			else
			{
				MessageCall.errorMessage("User not found !", "user_not_found");
				return "NotFound";
			}
		}
	}
	
	public void handleFileUpload(FileUploadEvent event) throws NamingException,
	IOException {
		ExternalContext extContext = FacesContext.getCurrentInstance()
				.getExternalContext();
		
		File result = new File(extContext.getRealPath("//uploaded//IDImages//"
				+ acc.getAccID() + "_" + event.getFile().getFileName()));
		
		FileOutputStream fileOutputStream = new FileOutputStream(result);
		byte[] buffer = new byte[6124];
		int bulk;
		InputStream inputStream = event.getFile().getInputstream();
		while (true) {
			bulk = inputStream.read(buffer);
			if (bulk < 0) {
				break;
			}
			fileOutputStream.write(buffer, 0, bulk);
			fileOutputStream.flush();
		}
		fileOutputStream.close();
		inputStream.close();
		
		Context ctx = new InitialContext();
		AccountBeanRemote accRe = (AccountBeanRemote) ctx
				.lookup("MySweetHome/AccountBean/remote");
		
		if (acc.getIDImage() != null) {
			File del = new File(extContext.getRealPath(acc.getIDImage()));
			del.delete();
		}
		acc.setIDImage("//uploaded//IDImages//" + acc.getAccID() + "_"
				+ event.getFile().getFileName());
		accRe.updateBasicInfo(acc);
		this.setImageUploaded(true);
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Upload Successfully", "Upload Successfully");
		FacesContext.getCurrentInstance().addMessage("upload_form:IDUploader",
				message);
		
		}
	
	public void GetStatusVerified() 
	{
		if (this.acc.getIsVerified()) {
			this.setVerifiedString("Verified");
		} else if (!this.acc.getIsVerified()) {
			this.setVerifiedString("Not Verified");
		}
	}
	
	
	
	public void GetStaffAccType() 
	{
		if (!this.isAdmin) {
			this.setVerifiedString("Staff");
		} else if (this.isAdmin) {
			this.setVerifiedString("Admin");
		}
	}

}
